<template>
	<view class="contents">
		<navbar title='商家入驻'>
		</navbar>
		<view class="content">
			<view class="addtuan">
				<view class="aditem chuantu">
					<text class="addname">上传店铺LOGO</text>
					<text class="chuanmiao">上传店铺LOGO、品牌标志。</text>
					<view class="tuview">

						<view class="tuitem" v-if="formData.logo" @click.stop="getyulan(ossThree(formData.logo))">
							<image class="tuimg" :src="ossThree(formData.logo)" mode="" />
							<image class="del" @click.stop="deltu(1)" src="@/pages_client/static/img/del.png" mode="" />
						</view>
						<view class="tuitem" @click="upload(1)">
							<image class="icon_zp" src="@/pages_client/static/img/img_sc.png" mode="" />
							<text>上传LOGO</text>
						</view>
					</view>
				</view>
				<view class="aditem">
					<text class="addname">店铺名称</text>
					<u-input style="flex: 1;" v-model="formData.name" type="text" placeholder='请输入' />
				</view>
				<view class="aditem chuantu">
					<text class="addname">店铺介绍</text>
					<view class="jieshao">
						<u-input style="flex: 1;" v-model="formData.descript" type="textarea" placeholder='请输入' />
					</view>
				</view>
				<view class="aditem" @click="toCommunity">
					<text class="addname">店铺地址</text>
					<text class="qxze" :class="formData.address?'qactive':''">{{ formData.address?formData.address:'请选择' }}</text>
					<image class="comm_icon_next" src="@/pages_client/static/img/comm_icon_next.png" mode="" />
				</view>
				<view class="aditem" @click="getjy">
					<text class="addname">经营范围</text>
					<text class="qxze" :class="formData.cate_ids?'qactive':''">{{ formData.cate_ids?getMatchedNames(jylist,formData.cate_ids):'请选择' }}</text>
					<image class="comm_icon_next" src="@/pages_client/static/img/comm_icon_next.png" mode="" />
				</view>
				<view class="aditem chuantu">
					<text class="addname">上传店铺环境照片</text>
					<text class="chuanmiao">上传店铺背景图片，用于装修店铺主页。</text>
					<view class="tuview">

						<view class="tuitem" v-for="(item,index) in isArry(formData.images)" :key="index" @click="getyulan(ossThree(item))" v-if="formData.images">
							<image class="tuimg" :src="ossThree(item)" mode="" />
							<image class="del" @click.stop="del(index,2)" src="@/pages_client/static/img/del.png" mode="" />
						</view>
						<view class="tuitem" v-if="isArry(formData.images).length<tunum" @click="upload(2)">
							<image class="icon_zp" src="@/pages_client/static/img/img_sc.png" mode="" />
							<text>上传照片</text>
						</view>
					</view>
				</view>
				<view class="aditem chuantu">
					<text class="addname">营业执照</text>
					<text class="chuanmiao">上传店铺营业执照</text>
					<view class="tuview">

						<view class="tuitem" v-if="formData.yyzz_image" @click.stop="getyulan(ossThree(formData.yyzz_image))">
							<image class="tuimg" :src="ossThree(formData.yyzz_image)" mode="" />
							<image class="del" @click.stop="deltu(3)" src="@/pages_client/static/img/del.png" mode="" />
						</view>
						<view class="tuitem" @click="upload(3)">
							<image class="icon_zp" src="@/pages_client/static/img/img_sc.png" mode="" />
							<text>上传照片</text>
						</view>
					</view>
				</view>

			</view>
			<view class="botview">
				<view class="tjia" @click="getnext">下一步</view>
			</view>
		</view>

		<u-select v-model="jypop" :list="jylist" @confirm="seconfirm"></u-select>
</view>
</template>

<script>
 import {
		baseUrl
	} from '@/utils/config.js';
export default {
	data() {
		return {
			jypop: false,
			jylist: [],
			name: '',
			formData: {
				id:'',
				name: '',
				address:'',
				lat:'',
				lng:'',
				cate_ids:'',
				images:'',//店铺环境照片
				logo:'',
				yyzz_image:'',//营业执照
				descript:''
			},
			// formData: {
			// 	name: '测试',
			// 	address:'测试地址',
			// 	lat:'123',
			// 	lng:'456',
			// 	cate_ids:'1',
			// 	descript:'介绍',
			// 	images:'/uploads/20250511/201fea0f1a9abe0097352b91130778b0.png',//店铺环境照片
			// 	logo:'/uploads/20250511/201fea0f1a9abe0097352b91130778b0.png',
			// 	yyzz_image:'/uploads/20250511/201fea0f1a9abe0097352b91130778b0.png',//营业执照
			// },
			cate_name:'',
			headimg:'',
			updatetype:1,
			tunum:5,//最多5张图
			shop_id:''
		}
	},
	onLoad(option) {
		this.getjingying();//经验范围
		if(option.shop_id){
			this.shop_id = option.shop_id
			this.formData.id = option.shop_id
			
		}
		
	},
	onShow() {
	},
	methods: {
		async huixian(){
			let res = await this.$u.api.getApply({
				shop_id:this.shop_id
			});
			this.formData = this.assignIfEqual(this.formData, res);
			console.log(this.formData)
		},
		assignIfEqual(target, source) {
			for (const key in source) {
				if (source.hasOwnProperty(key) && target.hasOwnProperty(key)) {
				target[key] = source[key];
				}
			}
			return target;
		},
		getyulan(e){
                uni.previewImage({
                    current: e, // 当前显示图片的 http 链接
                    urls: [e] // 需要预览的图片 http 链接列表
                });
            },
		async getjingying() {
			let res = await this.$u.api.getJyCate({
			});

			let data = res
			let shuzu = []
			for (let i in data) {
				let a = {}
				a.label = data[i].name
				a.value = data[i].id
				shuzu.push(a)
			}
			this.jylist = shuzu
			if(this.shop_id){
				this.huixian()
			}
		},
		getnext() {
			let status = true
			let formData = this.formData
			const result = this.checkObjectEmpty(formData);
		
			this.navrouter("/pages_client/mine/StoreEntryTwo?formData="+JSON.stringify(formData));
		},
		checkObjectEmpty(obj) {//检测是否为空
			for (let key in obj) {
				if (obj.hasOwnProperty(key)) {
					const value = obj[key];
					if(key == 'id'||key == 'shop_id'){
						return;
					}
					if (value === null || value === undefined || value === "") {
						uni.showToast({
							title: `请完善信息`,
							icon: 'none'
						});
						return true; // 只要有一个为空就返回true
					}
				}
			}
			return false; // 所有属性都不为空则返回false
		},
		getjy() {
			this.jypop = true
		},
		seconfirm(e) {
			console.log(e)
			console.log(this.checkContain(this.formData.cate_ids,e[0].value))
			if(this.checkContain(this.formData.cate_ids,e[0].value)){
				this.cate_name = this.appendWithComma(this.cate_name,e[0].label)
				this.formData.cate_ids = this.appendWithComma(this.formData.cate_ids,e[0].value) 
				console.log(this.formData.cate_ids)
			}
			
		},
		checkContain(mainStr, newStr) {
			// 将字符串按逗号分割成数组，然后检查新字符串是否在数组中
			const strArray = mainStr.split(',')
			// return strArray.some(str => str === newStr);
			let status = true
			for(let i in strArray){
				if(strArray[i] == newStr){
					status = false
				}
			}
			return status;
		},
		getMatchedNames(services, idsStr) {
			const ids = idsStr.split(',').map(id => parseInt(id.trim()));
			return ids.map(id => {
				const service = services.find(service => service.value == id);
				return service ? service.label : null;
			}).filter(label => label !== null).join(', ');
		},
		appendWithComma(target, appendStr) {
			if (target === "") {
				return appendStr;
			}
			return target + "," + appendStr;
		},
		checkValueInStr(str, value) {
			console.log(str)
			// if(str == ''){
			// 	return true;
			// }
			const arr = str.split(',');
			for (const item of arr) {
				if (item.trim() === value) {
					return false;
				}
			}
			return true;
		},
		toCommunity() {
			console.log("+++")
			const that = this
			uni.getSetting({
				success: (res) => {
					console.log(res)
					const status = res.authSetting
					// 如果当前设置是：不允许，则需要弹框提醒客户，需要前往设置页面打开授权
					if (!status['scope.userLocation']) {
						uni.showModal({
							title: "是否授权当前位置",
							content: "需要获取您的地理位置，请确认授权，否则地图功能将无法使用",
							success: (tip) => {
								if (tip.confirm) {
									// 如果已经拒绝过，则需要打开设置页面，授权弹框不会弹出第二次，因为已经明确拒绝/确认过了（微信的原因）
									if (that.isDeny) {
										uni.openSetting({
											success: function(res) {
												// 在设置页面授权成功后再次获取位置信息
												uni.showToast({
													title: "授权成功",
												})
												that.isDeny = false
												// 修改授权后返回页面，弹框消失，需要再点一次
											},
											fail: (data) => {
												console.log(data)
												// isDeny 是否拒绝过授权，如果拒绝过，再点击按钮的话，弹框确认后就直接打开微信小程序设置页
												that.isDeny = true
											}
										})
										return
									}
									// 如果点击了确认，并且没有拒绝过微信系统授权弹框，则会弹出授权位置信息的弹框
									uni.authorize({
										scope: "scope.userLocation",
										success: (data) => {
											// 授权弹框点击确认
											console.log(data)
											// 如果用户同意授权，则打开授权设置页面，判断用户的操作
											uni.openSetting({
												success: (data) => {
													// 如果用户授权了地理信息在，则提示授权成功
													if (data.authSetting['scope.userLocation'] === true) {
														uni.showToast({
															title: "授权成功",
															icon: "none",
															duration: 1000
														})
													}
												}
											})
										},
										fail: (data) => {
											// 如果用户拒绝授权，则提示用户需要授权
											uni.showToast({
												title: "您已拒绝授权，请重新授权",
												icon: "none",
												duration: 1000
											})
											that.isDeny = true
										}
									})
								}
							}
						})
					} else {
						uni.chooseLocation({
							success: (res) => {
								console.log(res)
								// that.formData.name = res.name
								that.formData.address = res.address+res.name
								that.formData.lng = res.longitude
								that.formData.lat = res.latitude
							},
							fail: (e) => {
								console.log(e)
							}
						})
					}
				},
				fail: () => {
					that.isDeny = true
				},
			})
		},
		upload(e) {
			this.updatetype = e
			uni.chooseImage({
				count: 1,
				success: (chooseImageRes) => {
					const tempFilePaths = chooseImageRes.tempFilePaths;
					this.headimg = tempFilePaths[0];
					// this.isClick = true;
					this.unloadtou()
				}
			});
		},
		unloadtou(){
			// console.log(this.head_portrait)
			let that = this
			uni.uploadFile({
				url: baseUrl + '/api/common/upload', //仅为示例，非真实的接口地址
				filePath: this.headimg,
				name: 'file',
				header: {
					// 'content-type': 'application/json;charset=UTF-8',
					'token': uni.getStorageSync('token'),
				},
				formData: {
					'token':uni.getStorageSync('token')
				},
				success: (uploadFileRes) => {
					if(JSON.parse(uploadFileRes.data).code == 1){
						if(that.updatetype == 1){
							that.formData.logo = JSON.parse(uploadFileRes.data).data.url
						}else if(that.updatetype == 2){
							let data = that.isArry(that.formData.images)
							data.push(JSON.parse(uploadFileRes.data).data.url)
							that.formData.images = data.toString()
							console.log(that.formData.images)
						}else if(that.updatetype == 3){
							that.formData.yyzz_image = JSON.parse(uploadFileRes.data).data.url
						}
						
					}else{
						that.$u.toast(JSON.parse(uploadFileRes.data).msg);
					}
					// that.getinfo()
				}
			});
		},
		isArry(e){
			let data = []
			if(e == ''){

			}else{
				data = e.split(",");
			}
			return data
		},
		deltu(index){//删除单张
			let that = this
			uni.showModal({
				title: '提示',
				content: '确定删除此张图片么？',
				cancelText: "取消", // 取消按钮的文字  
				confirmText: "确认", // 确认按钮的文字  
				// showCancel: false, // 是否显示取消按钮，默认为 true
				// confirmColor: '#f55850',
				// cancelColor: '#39B54A',
				success: (res) => {
				if(res.confirm) {  
					if(index == 1){
						//删除logo
						that.formData.logo = ''
					}else if(index == 3){
						that.formData.yyzz_image = ''
					}
				} else {  
					console.log('cancel') //点击取消之后执行的代码
					}  
				} 
			})
		},
		del(index,type){
			let that = this
			uni.showModal({
				title: '提示',
				content: '确定删除此张图片么？',
				cancelText: "取消", // 取消按钮的文字  
				confirmText: "确认", // 确认按钮的文字  
				// showCancel: false, // 是否显示取消按钮，默认为 true
				// confirmColor: '#f55850',
				// cancelColor: '#39B54A',
				success: (res) => {
				if(res.confirm) {  
					that.deltwo(index,type)
				} else {  
					console.log('cancel') //点击取消之后执行的代码
					}  
				} 
			})
		},
		deltwo(index,type){
			if(type == 2){
				//环境照片
				let shuzu = this.isArry(this.formData.images)
				shuzu.splice(index,1)
				this.formData.images = shuzu.toString()
			}
			
		}
	}
}
</script>

<style lang="scss" scoped>
page {
	background-color: #f9f9f9;
}

/deep/.u-drawer-bottom {
	background-color: #fff !important;
}

.content {
	background-color: #f9f9f9;
	min-height: 100vh;
	padding-bottom: 130rpx;
	padding-top: 20rpx;

	.comm_icon_next {
		margin-left: auto;
		width: 24rpx;
		height: 24rpx;
	}

	.qxze {
		color: #c0c4cc;
	}

	.qactive {
		color: #333;
	}

	.addtuan {
		display: flex;
		flex-direction: column;
		padding: 0 30rpx;

		.aditem {
			background: #FFFFFF;
			border-radius: 20rpx;
			padding: 10rpx 30rpx;
			display: flex;
			flex-direction: row;
			align-items: center;
			margin-bottom: 25rpx;
			min-height: 100rpx;


			.addname {
				font-weight: bold;
				font-size: 28rpx;
				color: #333333;
				display: inline-block;
				min-width: 120rpx;
			}

			.comm_icon_next {
				width: 24rpx;
				height: 24rpx;
				margin-left: auto;
			}
		}

		.chuantu {
			flex-direction: column;
			align-items: flex-start;
			padding: 25rpx 30rpx;

			.chuanmiao {
				font-weight: 500;
				font-size: 26rpx;
				color: #999999;
				display: block;
				margin: 10rpx 0 20rpx;
			}
		}

		.tuview {
			display: flex;
			flex-direction: row;
			flex-wrap: wrap;

			.tuitem {
				margin: 0 30rpx 0 0;
				width: 160rpx;
				height: 160rpx;
				background: #F8F8F8;
				border-radius: 20rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				flex-direction: column;
				position: relative;

				.icon_zp {
					width: 100%;
					height: 100%;
					position: absolute;
				}

				text {
					font-weight: 400;
					font-size: 24rpx;
					color: #525357;
					position: relative;
					margin-top: 80rpx;
				}

				.tuimg {
					position: absolute;
					width: 100%;
					height: 100%;
					border-radius: 20rpx;
				}
			}

			.dianpu {
				width: 320rpx;
				height: 220rpx;

				text {
					margin-top: 140rpx;
				}
			}

			.tuchuan {
				.icon_zp {
					position: absolute;
					width: 100%;
					height: 100%;
					border-radius: 20rpx;
					margin-bottom: 0;
				}
			}
		}
	}
}

.botview {
	position: fixed;
	height: 120rpx;
	width: 100%;
	bottom: 0;
	background-color: #fff;
	z-index: 10;
	padding: 0 30rpx;
	display: flex;
	align-items: center;

	.tjia {
		width: 100%;
		height: 90rpx;
		background: #52443B;
		border-radius: 16rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-weight: bold;
		font-size: 28rpx;
		color: #FFFFFF;
	}
}
.del{
	position: absolute;
	right: 0;
	bottom: 0;
	width: 39rpx;
	height: 39rpx;
}
.jieshao{
	background-color: #f9f9f9;
	padding:14rpx 30rpx;
	width: 100%;
	margin-top: 20rpx;
}
</style>
